package com.tjetc.utils;

import io.jsonwebtoken.*;

import java.sql.Date;
import java.util.UUID;

public class JwtUtil {
    //密钥
    private static String secret="19898933892";
    //设置token
    public  static String createToken(String username){
        JwtBuilder builder = Jwts.builder();
        String token=builder
                //header
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //payload
                .claim("username", username)
                .setSubject("xxx")
                .setExpiration(new Date(System.currentTimeMillis() +2*1000*3600))
                .setId(UUID.randomUUID().toString())
                //signature
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
        return token;
    }


    public static boolean isValid(String token){
        try {
            //解析token：开锁
            Claims body=Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            return true;
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
        } catch (UnsupportedJwtException e) {
            e.printStackTrace();
        } catch (MalformedJwtException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return false;

    }
    public static Claims  parseJwt(String token)  {
        //解析
        try {
            Jws<Claims> jws = Jwts.parser()//得到解析对象
                    .setSigningKey(secret) //设置解析时使用的秘钥
                    .parseClaimsJws(token);//解析
            return  jws.getBody();
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
        } catch (UnsupportedJwtException e) {
            e.printStackTrace();
        } catch (MalformedJwtException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return  null;
    }
}
